package com.shengdong.water.code.viewmodel

import androidx.lifecycle.viewModelScope
import com.shengdong.water.base.BaseViewModel
import com.shengdong.water.code.bean.MapDataBean
import com.shengdong.water.code.bean.MapOutletBean
import com.shengdong.water.code.bean.Outlet
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import com.shengdong.water.code.repository.ApiRepository
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

@HiltViewModel
class MapViewModel @Inject constructor(
    private val repository: ApiRepository
) : BaseViewModel() {


    private val _districts = MutableStateFlow<MapDataBean?>(null)
    val districts: StateFlow<MapDataBean?> = _districts


    private val _outlets = MutableStateFlow<MapOutletBean?>(null)
    val outlets: StateFlow<MapOutletBean?> = _outlets


    fun getDistricts() {
        handleRequest(
            flow = repository.getAdministrativeArea(0, "新建区"),
            onSuccess = {  println("MapViewModel: getDistricts获取数据成功")
                _districts.value = it },
            onError = { code ,msg ->
                when (code) {
                    401 ->  {}// 处理未授权
                    403 -> {}// 处理禁止访问
                    else -> showError(msg)
                }

            },
            onToast =  {
                it
            },
            onException = {e ->
                showError("发生错误: ${e.message}")
            },
        )
    }


    fun getOutletInfoOnMap() {
        viewModelScope.launch {
            handleRequest(
                flow = repository.getOutletInfoOnMap(),
                onSuccess = { println("MapViewModel: getOutletInfoOnMap获取数据成功")
                    _outlets.value = it },
                onError = { code ,msg ->
                    when (code) {
                        401 ->  {}// 处理未授权
                        403 -> {}// 处理禁止访问
                        else -> showError(msg)
                    }

                },
                onToast =  {
                    it
                },
                onException = {e ->
                    showError("发生错误: ${e.message}")
                },
            )
        }

    }

}